package cn.gson.crm.controller.onsales;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.gson.crm.model.dao.CustomerDao;
import cn.gson.crm.model.dao.EmployeeDao;
import cn.gson.crm.model.dao.OrderDao;
import cn.gson.crm.model.dao.ReceivableDao;
import cn.gson.crm.model.entity.Employee;
import cn.gson.crm.model.entity.Order;
import cn.gson.crm.model.entity.Receivable;
import cn.gson.crm.service.ReceivableService;

/**
 * 回款
 * 
 * @author hzl
 * @date 2018年4月13日
 * @time 上午10:35:06
 */
@Controller
@RequestMapping("crm/receivable")
public class ReceivableController {
	@Autowired
	ReceivableDao receivableDao;

	@Autowired
	OrderDao orderDao;

	@Autowired
	CustomerDao customerDao;
	
	@Autowired
	EmployeeDao empDao;
	
	@Autowired
	ReceivableService receivableService;

	/**
	 * 回款列表
	 * 
	 * @return
	 */
	@GetMapping
	public String receivableList() {
		return "onsales/order/receivable_list";
	}
	/**
	 * 回款计划
	 * @param page
	 * @param rows
	 * @return
	 */
	@RequestMapping("list")
	@ResponseBody
	public Map<String, Object> getlist(@RequestParam(defaultValue = "1") int page,
			@RequestParam(defaultValue = "20") int rows,HttpServletRequest req) {
		Employee emp=(Employee) req.getSession().getAttribute("employee");
		PageRequest pr = new PageRequest(page - 1, rows, new Sort(Direction.DESC, "id"));

		Page<Receivable> receivable;
		if("销售员".equals(emp.getRole().getRoleName())){
			receivable = receivableDao.findByEmployee(emp, pr);
		}else{
			receivable = receivableDao.findAll(pr);
		}
		Map<String, Object> data = new HashMap<>();
		data.put("rows", receivable.getContent());
		data.put("total", receivable.getTotalElements());
		return data;
	}

	/**
	 * 回款明细
	 * 
	 * @return
	 */
	@GetMapping("receivableDetail")
	public String receivableDetail() {
		return "onsales/order/receivable_detail_list";
	}
	//根据订单查出对应的回款计划
	@GetMapping("getReceivableByOrder")
	@ResponseBody
	public JSONArray getReceivableByOrder(@RequestParam(value="orderid") Long oid){
		System.out.println("这里执行了、、、、");
		JSONArray jsonArray=new JSONArray();
		Order order=orderDao.findOne(oid);
		List<Receivable> receivablelist=receivableDao.findByOrder(order);
		System.out.println("产股："+receivablelist.size());
		for (Receivable receivable : receivablelist) {
			jsonArray.add(receivable);
		}
		return jsonArray;
	}
	// 保存一条回款计划
	@PostMapping("save")
	@ResponseBody
	public JSONObject saveReceivable(@Valid Receivable receivable, BindingResult br, @RequestParam(value="customerid",required=false) Long cid,
			@RequestParam(value="orderid",required=false) Long oid, @RequestParam(value="time",required=false) String time,HttpServletRequest req) {
		System.out.println(receivable.toString());
		Employee emp=(Employee) req.getSession().getAttribute("employee");
		JSONObject result = new JSONObject();
		if (br.hasErrors()) {
			System.out.println(br);
			result.put("err", "校验失败！");
		} else {
			if (receivable.getId() == null) {//新增一条回款计划
				SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd ");
				Date date = null;
				try {
					date = formatter.parse(time);
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				receivable.setEmployee(emp);
				receivable.setPlanTime(date);
				receivable.setOrder(orderDao.findOne(oid));
				receivable.setCustomer(customerDao.findOne(cid));
				receivable.setState("未回款");
				receivableService.addReceivablEndPayTimeList(receivable);
			}else{//回款
				receivable.setPayee(emp);
				receivable.setActuaMoney(receivable.getPlanMoney());
				receivable.setActualTime(new Date());
				receivable.setState("已回款");
				receivableService.removeReceivablEndPayTimeList(receivable);
				//修改订单的已回款金额
				Order order=receivable.getOrder();
				order.setReceivableMoney(order.getReceivableMoney()+receivable.getPlanMoney());
				orderDao.save(order);
			}
			receivableDao.save(receivable);
			result.put("success", true);
		}
		return result;
	}
	//保存多条回款计划
	@PostMapping("savelist/{orderid}")
	@ResponseBody
	public JSONObject saveReceivableList(@RequestParam("param") String list,@PathVariable(name="orderid")Long orderid,HttpServletRequest req) {
		System.out.println("这里执行了、、、");
		JSONObject result = new JSONObject();
		Employee emp=(Employee) req.getSession().getAttribute("employee");
//		Employee emp=empDao.findOne(1L);
		Order order = orderDao.findOne(orderid);
		if(order==null){
			result.put("err", "保存失败！");
		}
		JSONArray jsonArray = JSONArray.parseArray(list);
		if (jsonArray.size() > 0) {
			for (int i = 0; i < jsonArray.size(); i++) {
				// 遍历 jsonarray 数组，把每一个对象转成 json 对象
				JSONObject obj = jsonArray.getJSONObject(i);
				Receivable receivable=new Receivable();
				
				receivable.setPlanTime(obj.getTimestamp("planTime"));
				receivable.setPlanMoney(obj.getDoubleValue("planMoney"));
				receivable.setInstallment(i+1);
				receivable.setNote(obj.getString("note"));
				receivable.setState("未回款");
				
				receivable.setEmployee(emp);
				receivable.setOrder(order);
				receivable.setCustomer(order.getCustomer());
				
				try {
					receivableService.addReceivablEndPayTimeList(receivable);
					receivableDao.save(receivable);
					result.put("success", "成功 ！");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					result.put("err", "保存失败！");
				}
				
			}
		}
		return result;
	}
}
